package com.justonetech.translation.controller;

import com.justonetech.core.controller.BaseCRUDActionController;
import com.justonetech.core.orm.hibernate.Page;
import com.justonetech.core.orm.hibernate.QueryTranslate;
import com.justonetech.core.utils.ReflectionUtils;
import com.justonetech.system.daoservice.SysDeptService;
import com.justonetech.system.daoservice.SysPersonDeptService;
import com.justonetech.system.daoservice.SysPersonService;
import com.justonetech.system.domain.SysDept;
import com.justonetech.system.domain.SysPerson;
import com.justonetech.system.domain.SysPersonDept;
import com.justonetech.system.domain.SysUser;
import com.justonetech.system.tree.Node;
import com.justonetech.system.tree.TreeBranch;
import com.justonetech.system.tree.ZTreeNode;
import com.justonetech.system.utils.Constants;
import com.justonetech.system.utils.UserSessionUtils;
import com.justonetech.translation.daoservice.*;
import com.justonetech.translation.domain.*;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @version 1.0
 * @author: System
 */
@Controller
public class TaskController extends BaseCRUDActionController<Task> {
    private static Log log = LogFactory.getLog(TaskController.class);
    private String [] statusStr = {"翻译中","审稿中","重新翻译","翻译完成"};
    private String [] status= {"1","2","3","4"};
    @Autowired
    private TaskService taskService;

    @Autowired
    private ProjectService projectService;

    @Autowired
    private SysPersonDeptService sysPersonDeptService;

    @Autowired
    private ContractService contractService;

    @Autowired
    private DocAttachmentsService docAttachmentsService;

    @Autowired
    private DocumentService documentService;

    @RequestMapping
    @ResponseBody
    public Page<Task> grid(Page page, String condition) {
        try {
            page.setAutoCount(true);
            String hql = "from Task t where 1=1 order by startDate desc" ;

            QueryTranslate queryTranslate = new QueryTranslate(hql, condition);
            HashMap <String,String>hashMap = new HashMap<String,String>();
            for(int i=0;i<statusStr.length;i++){
                hashMap.put(status[i],statusStr[i]);
            }
            // 查询
            page = taskService.findByPage(page, queryTranslate.toString());
            List<Task> rows = page.getRows();
            for (Task row : rows) {
                row.setStatus(hashMap.get(row.getStatus()));
            }
        } catch (Exception e) {
            log.error("error", e);
        }

        return page;
    }

    @RequestMapping
    @ResponseBody
    public Page<Task> newTaskGrid(Page page, String condition) {

        try {
            SysUser loginUser = UserSessionUtils.getInstance().getLoginedUser();

            SysPerson person = loginUser.getPerson();
            page.setAutoCount(true);
            String hql = "from Task t where t.translator.id="+ person.getId() +" and t.status!='"+ Constants.TASK_COMPLETED+ "' order by t.startDate desc" ;

            QueryTranslate queryTranslate = new QueryTranslate(hql, condition);
            HashMap <String,String>hashMap = new HashMap<String,String>();
            for(int i=0;i<statusStr.length;i++){
                hashMap.put(status[i],statusStr[i]);
            }
            // 查询
            page = taskService.findByPage(page, queryTranslate.toString());
            List<Task> rows = page.getRows();
            for (Task row : rows) {
                row.setStatus(hashMap.get(row.getStatus()));
            }
        } catch (Exception e) {
            log.error("error", e);
        }

        return page;
    }

    @RequestMapping
    @ResponseBody
    public Page<Task> historyTaskGrid(Page page, String condition) {

        try {
            SysUser loginUser = UserSessionUtils.getInstance().getLoginedUser();

            SysPerson person = loginUser.getPerson();
            page.setAutoCount(true);
            String hql = "from Task t where t.translator.id="+ person.getId() +" and t.status='"+ Constants.TASK_COMPLETED+ "' order by t.startDate desc" ;

            QueryTranslate queryTranslate = new QueryTranslate(hql, condition);
            HashMap <String,String>hashMap = new HashMap<String,String>();
            for(int i=0;i<statusStr.length;i++){
                hashMap.put(status[i],statusStr[i]);
            }
            // 查询
            page = taskService.findByPage(page, queryTranslate.toString());
            List<Task> rows = page.getRows();
            for (Task row : rows) {
                row.setStatus(hashMap.get(row.getStatus()));
            }
        } catch (Exception e) {
            log.error("error", e);
        }

        return page;
    }

    @RequestMapping
    @ResponseBody
    public Page<Task> reviewGrid(Page page, String condition) {

        try {
            SysUser loginUser = UserSessionUtils.getInstance().getLoginedUser();

            Set<SysPersonDept> sysPersonDepts = loginUser.getPerson().getSysPersonDepts();
            Iterator<SysPersonDept> sysPersonDeptIterator = sysPersonDepts.iterator();
            Long deptId = sysPersonDeptIterator.next().getDept().getId();
            String projectIds = "";
            String contractHql = "from Contract c where c.firstParty.id=" +deptId;
            List<Contract> contractList = contractService.findByQuery(contractHql);
            for (Contract contract : contractList) {
                projectIds += contract.getProject().getId()+",";
            }
            if(projectIds.length()>0){
                projectIds = projectIds.substring(0,projectIds.length()-1);
            }
            page.setAutoCount(true);
            String hql = "from Task t where t.project.id in("+ projectIds +") and t.status!='"+ Constants.TASK_COMPLETED + "' order by t.startDate desc" ;

            QueryTranslate queryTranslate = new QueryTranslate(hql, condition);
            HashMap <String,String>hashMap = new HashMap<String,String>();
            for(int i=0;i<statusStr.length;i++){
                hashMap.put(status[i],statusStr[i]);
            }
            // 查询
            page = taskService.findByPage(page, queryTranslate.toString());
            List<Task> rows = page.getRows();
            for (Task row : rows) {
                row.setStatus(hashMap.get(row.getStatus()));
            }
        } catch (Exception e) {
            log.error("error", e);
        }

        return page;
    }

    @RequestMapping
    public String init(Model model, Task entity,Long projectId) throws Exception {
        try {
            if(entity != null && entity.getId() != null) {
                entity = taskService.get(entity.getId());
//                entity.setProject(project);
                model.addAttribute("bean", entity);
            }else{
                entity = new Task();
                Project project = projectService.get(projectId);
                entity.setProject(project);
            }
            Map<String,String> linkedHashMap= new LinkedHashMap<String,String>();
            for(int i=0;i<statusStr.length;i++){
                linkedHashMap.put(status[i],statusStr[i]);
            }
            model.addAttribute("status",linkedHashMap.get(entity.getStatus()));
            model.addAttribute("statusItems",linkedHashMap);
            model.addAttribute("bean", entity);
        } catch (Exception e) {
            log.error("error", e);
        }

        return "view/tas/taskEdit";
    }

    @RequestMapping
    public String view(Model model, Long id) {
        Task task = taskService.get(id);
        HashMap <String,String>hashMap = new HashMap<String,String>();
        for(int i=0;i<statusStr.length;i++){
            hashMap.put(status[i],statusStr[i]);
        }
        task.setStatus(hashMap.get(task.getStatus()));
        model.addAttribute("bean", task);
        return "view/tas/taskView";
    }

    @RequestMapping
    public void save(HttpServletResponse response, Model model, @ModelAttribute("bean") Task entity)
            throws Exception {
        try {
            String[] columns = new String[]{
                    "id",
                    "name",
                    "tag",
                    "completeDate",
                    "startDate",
                    "endDate",
                    "wordCount",
                    "translator",
                    "reward",
                    "isEntrust",
                    "requirement",
                    "signDetail",
                    "reviewTeacher",
                    "reviewSugestion"
            };

            Task target;
            if (entity.getId() != null) {
                target = taskService.get(entity.getId());

                ReflectionUtils.copyBean(entity, target, columns);
                if(entity.getStatus()!=null){
                    target.setStatus(entity.getStatus());
                }
            } else {
                target = entity;  
                Document doc = target.getProject().getDoc();
                Long id = doc.getId();
                String hql = "from DocAttachments a where a.doc.id="+id;
                List<DocAttachments> attachmentses = docAttachmentsService.findByQuery(hql);
                Document document = new Document();
                documentService.save(document);
                for (DocAttachments attachment : attachmentses) {
                    DocAttachments docAttachments = new DocAttachments();
                    ReflectionUtils.copyBean(attachment,docAttachments,new String[]{
                            "name",
                            "orginName",
                            "uploadDate",
                            "remark",
                            "filePath"
                    });
                    docAttachments.setDoc(document);
                    docAttachmentsService.save(docAttachments);
                }
                target.setDoc(document);
                target.setStatus(Constants.TASK_DOING);
            }

            taskService.save(target);
            sendSuccessJSON(response, "保存成功");
        } catch (Exception e) {
            log.error("error", e);
            super.processException(response, e);
        }
    }

    @RequestMapping
    public void delete(HttpServletResponse response, Long id) throws Exception {
        taskService.delete(id);

        sendSuccessJSON(response, "删除成功");
    }

    @RequestMapping
    @ResponseBody
    public List<Task> getTaskList(Long id, Long projectId) {
        String hql = "from Task t where 1=1 ";

        if(id != null && id > 0) {
            hql += " and id = " + id;
        }

        if(projectId != null && projectId > 0) {
            hql += " and project.id = " + projectId;
        }

        hql += " order by t.id desc";

        return taskService.find(hql);
    }

    /**
     * 获取翻译人员
     * @param id
     * @param
     * @return
     */
    @RequestMapping
    @ResponseBody
    public List<Node> tree(String type,String uid, String id) throws Exception {
        TreeBranch treeBranch = new TreeBranch();
        type = StringUtils.defaultString(type, "");

        if(StringUtils.isEmpty(uid)) {
            ZTreeNode treeNode = new ZTreeNode();
            treeNode.setId("root");
            treeNode.setIsParent(true);
            treeNode.setIsLeaf(false);
            treeNode.setOpen(true);
            treeNode.setName("翻译人员");
            treeNode.setUid("root");
            treeBranch.addTreeNode(treeNode);
        } else if("root".equals(id)){
            //取单位节点
            String hql ="from SysPersonDept t where t.dept.type=" + Constants.COM_TRANSFERS;

            List<SysPersonDept> sysPersonDepts = sysPersonDeptService.findByQuery(hql);
            HashMap <Long,Integer> personCountMap = new HashMap<Long,Integer>() ;
            HashSet<SysDept> sysDepts = new HashSet<SysDept>();
            for (SysPersonDept sysPersonDept : sysPersonDepts) {
                int count = 0;
                Integer actCount = personCountMap.get(sysPersonDept.getDept().getId());
                if(actCount !=null){
                    count = actCount;
                }
                if(sysDepts.contains(sysPersonDept.getDept())){
                    count ++;
                }else{
                    sysDepts.add(sysPersonDept.getDept());
                    count++;
                }
                personCountMap.put(sysPersonDept.getDept().getId(),count);
            }
            for (SysDept sysDept : sysDepts) {
                ZTreeNode treeNode = new ZTreeNode();
                treeNode.setId(sysDept.getClass().getSimpleName() + "_" + sysDept.getId());
                if(personCountMap.get(sysDept.getId())>0){
                    treeNode.setIsParent(true);
                    treeNode.setOpen(false);
                }else{
                    treeNode.setIsLeaf(true);
                }
                treeNode.setName(sysDept.getName());
                treeNode.setText(sysDept.getName());
                treeNode.setUid(sysDept.getId().toString());
                treeNode.setType(sysDept.getClass().getSimpleName());
                treeBranch.addTreeNode(treeNode);
            }
        } else if(id.indexOf("SysDept")>=0){
            List<SysPersonDept> sysPersonDepts = sysPersonDeptService.findByQuery("from SysPersonDept where dept.id=" + uid);
            for (SysPersonDept sysPersonDept : sysPersonDepts) {
                ZTreeNode treeNode = new ZTreeNode();
                treeNode.setId(sysPersonDept.getPerson().getClass().getSimpleName() + "_" + sysPersonDept.getPerson().getId());
                treeNode.setIsLeaf(true);
                treeNode.setName(sysPersonDept.getPerson().getName());
                treeNode.setText(sysPersonDept.getPerson().getName());
                treeNode.setUid(sysPersonDept.getPerson().getId().toString());
                treeNode.setType(sysPersonDept.getPerson().getClass().getSimpleName());
                treeBranch.addTreeNode(treeNode);
            }
        }

        return treeBranch.getTreeNodeList();
    }
}